﻿Imports Equipment.Core
Imports Equipment.DataAccess
Imports Equipment.Business
Imports AppUser = Equipment.DataAccess.User
Imports Equipment.Model

Namespace Equipment
    <RequiresAuthentication()> _
    Public Class ConfigurationController
        Inherits System.Web.Mvc.Controller

        Function Index() As ActionResult
            Return View("Users")
        End Function

        <RequiresPageAcces(Page:=PageType.HolidayDefinition)> _
        Function HolidayDefinition() As ActionResult
            ViewData("Holidays") = Holiday.RetrieveAll()
            ViewData("EntityType") = EntityType.Holiday
            Return View()
        End Function

#Region "Others"
        <RequiresPageAcces(Page:=PageType.Others)> _
        Function Others() As ActionResult
            ViewData("RequiredAuthentication") = Sys.RequiredAuthenticationForWorkOrder
            ViewData("ChangePassword") = Sys.RequestPasswordChange
            Return View()
        End Function

        <HttpPost()> _
        <RequiresPageAcces(Page:=PageType.Others)> _
        Function Others(ByVal collection As FormCollection) As ActionResult
            Dim Check As String = collection("CheckWorkOrderAuthentication")
            If Check.Split(",")(0) = "true" Then
                Sys.RequiredAuthenticationForWorkOrder = True
                Application.CurrentUserInfo.RequiredAuthenticationForWorkOrder = True
            Else
                Sys.RequiredAuthenticationForWorkOrder = False
                Application.CurrentUserInfo.RequiredAuthenticationForWorkOrder = False
            End If
            Dim change As Integer = Integer.Parse(collection("ChangePassword"))
            Sys.RequestPasswordChange = change
            ViewData("Success_Mess") = "Values have been saved successfully."
            ViewData("RequiredAuthentication") = Sys.RequiredAuthenticationForWorkOrder
            ViewData("ChangePassword") = change
            Return View()
        End Function
#End Region


#Region "Asset Types, Statuses, Custom Fields "

        '
        ' GET: /Configuration
        Function AssetTypesStatusesFields() As ActionResult

            Dim customTextFieldsToInit As New List(Of AssetCustomField)
            Dim customDDFieldsToInit As New List(Of AssetCustomField)
            Dim predefinedFieldToInit As New List(Of AssetPredefinedFieldLookup)

            Dim customTextFieldList = AssetCustomField.RetrieveAllByType(CustomFieldType.Text)
            Dim customDDFieldList = AssetCustomField.RetrieveAllByType(CustomFieldType.DropDown)
            Dim predefinedFieldList = AssetCustomField.RetrieveAllByType(CustomFieldType.Predefined)

            For i As Integer = 1 To 10
                Dim txtItem As New AssetCustomField()
                Dim ddlItem As New AssetCustomField()

                Dim txt As AssetCustomField = customTextFieldList.SingleOrDefault(Function(f) f.SequenceID = i)
                Dim ddl As AssetCustomField = customDDFieldList.SingleOrDefault(Function(f) f.SequenceID = i)

                If txt IsNot Nothing Then
                    txtItem.ID = txt.ID
                    txtItem.FieldName = txt.FieldName
                    txtItem.Mandatory = txt.Mandatory
                    txtItem.FieldType = txt.FieldType
                    txtItem.SequenceID = txt.SequenceID
                    txtItem.IsActive = txt.IsActive
                Else
                    txtItem.SequenceID = i
                End If

                If ddl IsNot Nothing Then
                    ddlItem.ID = ddl.ID
                    ddlItem.FieldName = ddl.FieldName
                    ddlItem.Mandatory = ddl.Mandatory
                    ddlItem.FieldType = ddl.FieldType
                    ddlItem.Values = ddl.Values
                    ddlItem.SequenceID = ddl.SequenceID
                    ddlItem.IsActive = ddl.IsActive
                Else
                    ddlItem.SequenceID = i
                End If

                customTextFieldsToInit.Add(txtItem)
                customDDFieldsToInit.Add(ddlItem)
            Next

            For Each field In AssetPredefinedFieldLookup.RetrieveAll()
                Dim seq As Integer = CInt(field.Type)
                Dim dbField As AssetCustomField = predefinedFieldList.SingleOrDefault(Function(f) f.SequenceID = seq)

                If dbField IsNot Nothing Then
                    field.Selected = dbField.Mandatory
                Else
                    field.Selected = False
                End If
                predefinedFieldToInit.Add(field)
            Next
            Dim statuses = AssetStatus.RetrieveAll()
            Dim active = statuses.FirstOrDefault(Function(s) s.IsActive = True)
            ViewData("CustomTextFields") = customTextFieldsToInit
            ViewData("CustomDDFields") = customDDFieldsToInit
            ViewData("PredefinedFields") = predefinedFieldToInit
            ViewData("AssetTypes") = AssetType.RetrieveAll()

            If active IsNot Nothing Then
                ViewData("DDAssetStatus") = New SelectList(statuses, "ID", "Description", active.ID)
            Else
                ViewData("DDAssetStatus") = New SelectList(statuses, "ID", "Description")
            End If

            ViewData("AssetStatuses") = statuses

            Return View()
        End Function


        Private Sub UpdateCustomField(ByRef customField As AssetCustomField, ByVal seq As Integer, ByVal fieldName As String, _
                            ByVal isActive As Boolean, ByVal isMandatory As Boolean, ByVal values As String, ByVal type As CustomFieldType)

            Dim changeDetails As New List(Of String)

            Dim toInsert As Boolean = False
            Dim mandatortFlagChanged As Boolean = False
            Dim isAdded As Boolean = False
            Dim oldName As String = String.Empty

            If customField Is Nothing Then
                toInsert = True
                customField = New AssetCustomField()
            Else
                oldName = customField.FieldName
            End If

            If isMandatory <> customField.Mandatory AndAlso type = CustomFieldType.Predefined Then
                mandatortFlagChanged = True
            End If

            If customField.IsActive = False AndAlso isActive = True Then
                isAdded = True
            End If

            customField.FieldName = fieldName
            customField.IsActive = isActive
            customField.Mandatory = isMandatory
            customField.Values = values
            customField.SequenceID = seq
            customField.FieldType = type

            If toInsert Then
                AssetCustomField.Insert(customField)
                If type <> CustomFieldType.Predefined Then
                    NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.AssetCustomField_Create, customField.FieldName)
                End If
            Else
                customField.Save()
                If mandatortFlagChanged Then
                    NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.AssetCustomField_ModifyMandatoryFlag, customField.FieldName)
                End If
                If oldName <> customField.FieldName Then
                    NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.AssetCustomField_Modify, oldName)
                End If
                If isAdded = True Then
                    NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.AssetCustomField_Create, customField.FieldName)
                End If
            End If

        End Sub
#End Region

#Region "AJAX Section"

#Region "Custom Fields"
        <HttpPost()> _
        Function SaveCustomFields(ByVal collection As FormCollection) As ActionResult

            Dim changeDetails As New List(Of String)

            Try
                For i As Integer = 1 To 10

                    Dim txtFieldName = collection(String.Format("txtCustomTextField_{0}", i))
                    Dim isTextActive As Boolean = Boolean.Parse(CStr(collection(String.Format("cbxUseCustomTextField_{0}", i))).Split(",")(0))
                    Dim isTextMandatory As Boolean = Boolean.Parse(CStr(collection(String.Format("cbxMandatoryCustomTextField_{0}", i))).Split(",")(0))

                    Dim ddlFieldName = collection(String.Format("txtCustomDDField_{0}", i))
                    Dim isDDActive As Boolean = Boolean.Parse(CStr(collection(String.Format("cbxUseCustomDDField_{0}", i))).Split(",")(0))
                    Dim isDDMandatory As Boolean = Boolean.Parse(CStr(collection(String.Format("cbxMandatoryCustomDDField_{0}", i))).Split(",")(0))
                    Dim values = collection(String.Format("txtCustomDDFieldValues_{0}", i))


                    Dim txt As AssetCustomField = AssetCustomField.GetFirst(i, CustomFieldType.Text)
                    Dim ddl As AssetCustomField = AssetCustomField.GetFirst(i, CustomFieldType.DropDown)


                    If values Is Nothing Then
                        values = String.Empty
                    End If
                    If txtFieldName Is Nothing Then
                        txtFieldName = String.Empty
                    End If
                    If ddlFieldName Is Nothing Then
                        ddlFieldName = String.Empty
                    End If

                    If txt IsNot Nothing AndAlso txt.IsActive <> isTextActive Then
                        If isTextActive Then
                            changeDetails.Add(String.Format("Added text field {0}", txtFieldName))
                        Else
                            changeDetails.Add(String.Format("Deleted text field {0}", txtFieldName))
                        End If
                    ElseIf txt Is Nothing AndAlso isTextActive Then
                        changeDetails.Add(String.Format("Added text field {0}", txtFieldName))
                    End If

                    If ddl IsNot Nothing AndAlso ddl.IsActive <> isDDActive Then
                        If isDDActive Then
                            changeDetails.Add(String.Format("Added dropdown field {0}", ddlFieldName))
                        Else
                            changeDetails.Add(String.Format("Deleted dropdown field {0}", ddlFieldName))
                        End If
                    ElseIf ddl Is Nothing AndAlso isDDActive Then
                        changeDetails.Add(String.Format("Added dropdown field {0}", ddlFieldName))
                    End If

                    If isTextActive Then
                        If txt IsNot Nothing AndAlso txt.FieldName <> txtFieldName Then
                            changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, txt.FieldName, txt.FieldName, txtFieldName))
                        End If

                        If txt IsNot Nothing AndAlso txt.Mandatory <> isTextMandatory Then
                            changeDetails.Add(String.Format("Field - {0}. <br /> Mandatory flag.<br /> changed from: {1}<br />Changed to: {2}.", txt.FieldName, txt.Mandatory, isTextMandatory))
                        End If

                    End If

                    If isDDActive Then
                        If ddl IsNot Nothing AndAlso ddl.FieldName <> ddlFieldName Then
                            changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, ddl.FieldName, ddl.FieldName, ddlFieldName))
                        End If

                        If ddl IsNot Nothing AndAlso ddl.Mandatory <> isDDMandatory Then
                            changeDetails.Add(String.Format("Field - {0}. <br /> Mandatory flag.<br /> changed from: {1}<br />Changed to: {2}.", txt.FieldName, ddl.Mandatory, isDDMandatory))
                        End If
                    End If

                    UpdateCustomField(txt, i, txtFieldName, isTextActive, isTextMandatory, String.Empty, CustomFieldType.Text)
                    UpdateCustomField(ddl, i, ddlFieldName, isDDActive, isDDMandatory, values, CustomFieldType.DropDown)
                Next

                For Each field In AssetPredefinedFieldLookup.RetrieveAll()
                    Dim seq As Integer = CInt(field.Type)
                    Dim isMandatory As Boolean = Boolean.Parse(CStr(collection(String.Format("cbxMandatoryPredefinedField_{0}", seq))).Split(",")(0))
                    Dim pf As AssetCustomField = AssetCustomField.GetFirst(seq, CustomFieldType.Predefined)
                    If pf IsNot Nothing AndAlso pf.Mandatory <> isMandatory Then
                        changeDetails.Add(String.Format("Field - {0}. <br /> Mandatory flag.<br /> changed from: {1}<br />Changed to: {2}.", pf.FieldName, pf.Mandatory, isMandatory))
                    End If
                    UpdateCustomField(pf, seq, field.Description, True, isMandatory, String.Empty, CustomFieldType.Predefined)
                Next

                ModificationHistory.Insert(EntityType.AssetCustomField, "Asset Custom Fields", ModificationAction.Modified, Application.CurrentUserInfo.UserID, changeDetails, 0)

            Catch ex As Exception
                Return Content("<span class='error'>Inner exception accured:" & ex.Message & ".</span>")
            End Try

            Return Content("<span class='success'>All fields have been updated successfuly.</span>")
        End Function
#End Region

#Region "Asset"
        <HttpPost()> _
        <RequiresPageAcces(Page:=PageType.AssetType)> _
        Function SaveAssetType(ByVal currAssetTypeID As Integer, ByVal txtTypeDesc As String) As ActionResult

            Dim changeDetails As New List(Of String)

            Try
                If currAssetTypeID = 0 Then
                    Dim newAssetType As AssetType = AssetType.Insert(txtTypeDesc)
                    ViewData("StatusMsg") = "<span class='success'>Asset Type has been added successfuly.</span>"
                    ModificationHistory.Insert(EntityType.AssetType, txtTypeDesc, Application.CurrentUserInfo.UserID, newAssetType.ID)
                    NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.AssetType_Create, txtTypeDesc)
                Else
                    Dim assetTypeToUpdate As AssetType = AssetType.GetByPrimaryKey(currAssetTypeID)

                    If assetTypeToUpdate.Description <> txtTypeDesc Then
                        changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Description", assetTypeToUpdate.Description, txtTypeDesc))
                    End If
                    assetTypeToUpdate.Description = txtTypeDesc
                    assetTypeToUpdate.Save()
                    ViewData("StatusMsg") = "<span class='success'>Asset Type has been updated successfuly.</span>"
                    ModificationHistory.Insert(EntityType.AssetType, txtTypeDesc, ModificationAction.Modified, Application.CurrentUserInfo.UserID, changeDetails, assetTypeToUpdate.ID)
                    NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.AssetType_Modify, txtTypeDesc)
                End If
                ViewData("AssetTypes") = AssetType.RetrieveAll()
                Return PartialView("~/Views/Configuration/Controls/AssetTypeList.ascx", ViewData("AssetTypes"))

            Catch ex As Exception
                Return Content("<span class='error'>Inner exception accured:" & ex.Message & ".</span>")
            End Try
        End Function

        <HttpPost()> _
        Function SaveAssetStatus(ByVal currAssetStatusID As Integer, ByVal txtStatusDesc As String) As ActionResult

            Dim changeDetails As New List(Of String)

            Try
                If currAssetStatusID = 0 Then
                    Dim newAssetStatus As AssetStatus = AssetStatus.Insert(txtStatusDesc)
                    ViewData("StatusMsg") = "<span class='success'>Asset Status has been added successfuly.</span>"
                    ModificationHistory.Insert(EntityType.AssetStatus, txtStatusDesc, Application.CurrentUserInfo.UserID, newAssetStatus.ID)
                    NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.AssetStatus_Create, txtStatusDesc)
                Else
                    Dim assetStatusToUpdate As AssetStatus = AssetStatus.GetByPrimaryKey(currAssetStatusID)
                    If assetStatusToUpdate.Description <> txtStatusDesc Then
                        changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Description", assetStatusToUpdate.Description, txtStatusDesc))
                    End If
                    assetStatusToUpdate.Description = txtStatusDesc
                    assetStatusToUpdate.Save()
                    ViewData("StatusMsg") = "<span class='success'>Asset Status has been updated successfuly.</span>"
                    ModificationHistory.Insert(EntityType.AssetStatus, txtStatusDesc, ModificationAction.Modified, Application.CurrentUserInfo.UserID, changeDetails, assetStatusToUpdate.ID)
                    NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.AssetStatus_Modify, txtStatusDesc)
                End If
                Dim statuses = AssetStatus.RetrieveAll()
                ViewData("AssetStatuses") = statuses
                Dim active = statuses.FirstOrDefault(Function(s) s.IsActive = True)
                If active IsNot Nothing Then
                    ViewData("DDAssetStatus") = New SelectList(statuses, "ID", "Description", active.ID)
                Else
                    ViewData("DDAssetStatus") = New SelectList(statuses, "ID", "Description")
                End If
                Return PartialView("~/Views/Configuration/Controls/AssetStatusList.ascx", ViewData("AssetStatuses"))

            Catch ex As Exception
                Return Content("<span class='error'>Inner exception accured:" & ex.Message & ".</span>")
            End Try
        End Function

        <HttpPost()> _
        <RequiresPageAcces(Page:=PageType.AssetType)> _
        Function SetAssetStatusAsActive(ByVal assetStatusID As Integer) As ActionResult

            Try
                Dim statusToUpdate As AssetStatus = Nothing
                Dim statuses = AssetStatus.RetrieveAll()
                For Each status In statuses
                    If status.ID <> assetStatusID Then
                        status.IsActive = False
                    Else
                        statusToUpdate = status
                        status.IsActive = True
                    End If
                    status.Save()
                Next
                If statusToUpdate IsNot Nothing Then
                    ModificationHistory.Insert(EntityType.AssetStatus, statusToUpdate.Description, ModificationAction.Modified, Application.CurrentUserInfo.UserID, "Status was set to Active", statusToUpdate.ID)
                    ViewData("StatusMsg") = String.Format("<span class='success'>Asset Status <b>{0}</b> has been set as Active successfuly.</span>", statusToUpdate.Description)
                End If

                ViewData("AssetStatuses") = statuses
                ViewData("DDAssetStatus") = New SelectList(statuses, "ID", "Description", assetStatusID)

                Return PartialView("~/Views/Configuration/Controls/AssetStatusList.ascx")

            Catch ex As Exception
                Return Content("<span class='error'>Inner exception accured:" & ex.Message & ".</span>")
            End Try
        End Function
#End Region

#Region "Holiday"
        <HttpPost()> _
        <RequiresPageAcces(Page:=PageType.HolidayDefinition)> _
        Function SaveHoliday(ByVal currHolidayID As Integer, ByVal holidayDate As DateTime, ByVal holidayDesc As String) As ActionResult

            Try
                If currHolidayID = 0 Then
                    Dim changeDetails As New List(Of String)
                    changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, "Description", holidayDesc))
                    changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, "Date", holidayDate))
                    Dim newHoliday As Holiday = Holiday.Insert(holidayDate, holidayDesc)
                    ModificationHistory.Insert(EntityType.Holiday, holidayDesc, Application.CurrentUserInfo.UserID, newHoliday.ID)
                    NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.Holiday_Create, holidayDesc)
                Else
                    Dim changeDetails As New List(Of String)
                    Dim holidayToUpdate As Holiday = Holiday.GetByPrimaryKey(currHolidayID)
                    Dim oldDesc = holidayToUpdate.Description
                    Dim oldDate = holidayToUpdate.HolidayDate
                    holidayToUpdate.Description = holidayDesc
                    holidayToUpdate.Save()

                    If oldDesc <> holidayToUpdate.Description Then
                        changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Description", oldDesc, holidayDesc))
                    End If

                    If oldDate <> holidayToUpdate.HolidayDate Then
                        changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Date", oldDate, holidayToUpdate.HolidayDate))
                    End If


                    ModificationHistory.Insert(EntityType.Holiday, holidayDesc, ModificationAction.Modified, Application.CurrentUserInfo.UserID, changeDetails, holidayToUpdate.ID)
                    NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.Holiday_Modify, oldDesc)
                End If
                ViewData("Holidays") = Holiday.RetrieveAll()
                Return PartialView("~/Views/Configuration/Controls/HolidayList.ascx", ViewData("Holidays"))

            Catch ex As Exception
                Return Content("<span class='error'>Inner exception accured:" & ex.Message & ".</span>")
            End Try
        End Function

        <HttpPost()> _
<RequiresPageAcces(Page:=PageType.HolidayDefinition)> _
        Function DeleteHoliday(ByVal id As Integer) As ActionResult
            Dim respResult As New JSONActionResult
            respResult.Result = Result.SUCCESS
            Try
                Dim currHoliday As Holiday = Holiday.GetByPrimaryKey(id)
                currHoliday.Delete()
                ModificationHistory.Insert(EntityType.Holiday, currHoliday.Description, ModificationAction.Deleted, Application.CurrentUserInfo.UserID, String.Empty, id)

            Catch ex As Exception
                respResult.Result = Result.ERROR
                respResult.Message = ex.Message
            End Try

            Return Json(respResult)
        End Function
#End Region

#End Region

    End Class
End Namespace